package com.shanjupay.merchant.service.impl;


import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    //从配置文件中进行获取请求验证码服务的地址url和验证码有效期
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private String effectiveTime;
    @Autowired
    RestTemplate restTemplate;

   /*
   * 获取验证码
   *
   *
   * */
    @Override
    public String sendMsg(String phone) {
        //请求验证码的url地址
        String url =  smsUrl+"/generate?name=sms&effectiveTime="+effectiveTime;
        //构造请求实体
        //2.1构造请求体
        HashMap<String, Object> body = new HashMap<>();
        //存放手机号
        body.put("mobile",phone);
        //2.2构造请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置请求头的contentType
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        //请求体和请求头作为构造参数添加到请求实体中
        HttpEntity httpEntity = new HttpEntity(body, httpHeaders);
        //restTemplate发送restful风格的请求验证码服务进行发送验证码请求
        Map responseMap;
        try{
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
            log.info("调用短信微服务发送验证码:返回值为{}", JSON.toJSONString(exchange));
            //获取向请求验证码服务发送验证码中响应结果
            responseMap = exchange.getBody();

        }catch (Exception e){
            log.info(e.getMessage(),e);
            //throw new RuntimeException("发送验证码错误");
            throw new BusinessException(CommonErrorCode.E_100107);
        }

        //第二种异常：响应结果没有内容，或者响应结果result这个key为空值
        if(responseMap  == null &&  responseMap.get("result") == null){
            //throw  new RuntimeException("发送验证码出错");
            throw new BusinessException(CommonErrorCode.E_100107);
        }

        //获取响应结果 里面 result这个key 里面的 验证码的key
        Map resultMap = (Map) responseMap.get("result");
        return resultMap.get("key").toString();
    }

    /*校验验证码
    *
    *
    * */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) {
        //"http://localhost:56085/sailing/verify?name=sms&verificationCode="+verifiyCode+"&verificationKey="+verifiyKey;
        //1定义发送校验验证码的服务器地址 及携带请求参数
        String url = smsUrl+"/verify?name=sms&verificationCode="+verifiyCode+"&verificationKey="+verifiyKey;
        //初始化校验验证码响应map
        Map responseMap = null;
        try {
            //2校验验证码携带请求参数没有请求体，httpEntity就为空
            //使用restTemplate发送请求到验证码服务器校验验证码接口
            ResponseEntity<Map> exchange =   restTemplate.exchange(url, HttpMethod.POST,HttpEntity.EMPTY, Map.class);
            responseMap = exchange.getBody();
            log.info("校验验证码，响应结果{}",JSON.toJSONString(responseMap));
        }catch (Exception e){
            e.printStackTrace();
            //throw new RuntimeException("校验验证码失败");
            throw new BusinessException(CommonErrorCode.E_100102);
        }
        //第二种校验失败 ，响应结果数据为空 里面json中result的key的值为空 result为false
        if(responseMap == null || responseMap.get("result") == null || !(Boolean) responseMap.get("result")){
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }
}
